//
//  HKWebViewController.m
//  HKUtilities
//
//  Created by 胡锦涛 on 2018/11/14.
//  Copyright © 2018 胡锦涛. All rights reserved.
//

#import "HKWebViewController.h"
#import "HKPrefixHeader.h"
@interface HKWebViewController ()
@end

@implementation HKWebViewController
static bool isFirst = YES;
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self setNavBarHidden:NO];
    if (isFirst) {
        isFirst = NO;
    }else{
        if (!self.webView.title.length) {
            NSLog(@"网页需要刷新");
            [self reload];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initUI];
}

- (void)initUI {
    
    self.view.backgroundColor = [UIColor clearColor];
    //设置导航
    self.webView = [[HKWebView alloc] initWithFrame:CGRectMake(0, HK_NAVBAR_HEIGHT + HK_NO_NAV_HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT - HK_NAVBAR_HEIGHT - HK_NO_NAV_HEIGHT) delegate:self];
    HKAdjustsContentInsets(self.webView.scrollView);
    [self.view addSubview:self.webView];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    if (!_otherLink) {
        UIView *stausView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 20)];
        [stausView setBackgroundColor:COLOR_MAIN];
        [self.webView setFrame:CGRectMake(0, 20, SCREEN_WIDTH, SCREEN_HEIGHT - 20)];
        [self.webView.scrollView setBounces:NO];
        [self.view addSubview:stausView];
        [self.progressView removeFromSuperview];
    }
    if ([self.urlString length]) {
        [self loadWithUrl:self.urlString];
    }
    
}
- (void)setTitleName:(NSString *)titleName {
    _titleName = titleName;
    self.navigationItem.title = _titleName;
}

#pragma mark --- WKNavigationDelegate----
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    NSString *errorMessage =@"网络连接失败，请检查网络...\n轻触屏幕重试";
    if (self.navigationController.isNavigationBarHidden) {
        [self.navigationController setNavigationBarHidden:NO animated:NO];
    }
    HKWeakSelf
    [self.loadingView showErrorMessage:errorMessage WithRetry:^{
        HKStrongSelf
        [self reload];
    }];
    
}

// 决定导航的动作，通常用于处理跨域的链接能否导航。WebKit对跨域进行了安全检查限制，不允许跨域，因此我们要对不能跨域的链接
// 单独处理。但是，对于Safari是允许跨域的，不用这么处理。
//请求前
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    /**
     *WKNavigationActionPolicyCancel, 取消这次请求
     WKNavigationActionPolicyAllow, 继续
     */
    self.progressView.alpha = 1.0;
    //NSLog(@"navigationType  %d",navigationAction.navigationType);
    //NSLog(@"网页加载   %@", navigationAction.request.URL);
    
    NSString *u = navigationAction.request.URL.absoluteString;
    if (self.urlString && ![self.urlString isEqualToString:u]) {
        self.urlString = u;
        //NSLog(@"allHTTPHeaderFields %@",navigationAction.request.allHTTPHeaderFields[@"Cookie"]);
        [self loadWithUrl:self.urlString];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    //处理 Url
    if ([navigationAction.request.URL.scheme isEqualToString:HK_APP_SCHEME]) {
        //NSString *url = navigationAction.request.URL.absoluteString;
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    if(!([navigationAction.request.URL.scheme isEqualToString:@"http"] || [navigationAction.request.URL.scheme isEqualToString:@"https"])){
        if([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]){
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
            });
            decisionHandler(WKNavigationActionPolicyCancel);
            return;
        }
    }
    
    //如果是225进来的，就不需要拦截
    if (_otherLink) {
        self.urlString = navigationAction.request.URL.absoluteString;
        decisionHandler(WKNavigationActionPolicyAllow);
        return;
    }
    
    decisionHandler(WKNavigationActionPolicyCancel);
}

- (void)didReceiveMemoryWarning {
    
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc{
    isFirst = YES;
    [self.webView removeObserver:self forKeyPath:@"title" context:nil];
}

@end
